﻿Imports System.Data.SqlClient

Public Class Form1
    Private Sub Form1_Load(
      ByVal sender As Object,
      ByVal e As System.EventArgs) _
      Handles Me.Load
        Me.SqlConnection1.ConnectionString =
          "Integrated Security=SSPI;" &
          "Persist Security Info=False;" &
          "User ID='';" &
          "Initial Catalog=NorthWind;" &
          "Data Source=HP;" &
          "Initial File Name=''"
    End Sub

    Private Sub btnInserisciRecord_Click(
            sender As Object, e As EventArgs) _
            Handles btnInserisciRecord.Click
        Dim SQL As String = ""

        ' Lettura del valore più alto di ID
        SQL = "SELECT TOP 1 ID " &
              "FROM Clienti " &
              "ORDER BY ID DESC"
        Me.SqlConnection1.Open()
        Dim Comando As New SqlCommand(
          SQL, Me.SqlConnection1)
        Dim ID As Integer =
          Convert.ToInt32(Comando.ExecuteScalar)
        Me.SqlConnection1.Close()

        ' Definizione nuovo ID
        ID += 1

        ' Scrittura di un nuovo record
        SQL = "INSERT INTO " &
                "[NorthWind].[dbo].[Clienti] " &
                "([ID], " &
                "[Nome], " &
                "[Cognome], " &
                "[Indirizzo], " &
                "[Città]) " &
              "VALUES(" & ID.ToString & ", " &
                "'Giuseppe', " &
                "'Verdi', " &
                "'Via Rossi, 17', " &
                "'ROMA')"
        Me.SqlConnection1.Open()
        Comando = New SqlCommand(SQL, Me.SqlConnection1)
        Dim Numero As Integer = Comando.ExecuteNonQuery
        Me.SqlConnection1.Close()
        Me.Label1.Text = "Inserimento eseguito!"
    End Sub
End Class
